# -*- coding: utf-8 -*-
# @Env    : v-3.5.4
# @File   : models.py
# @Author : Kevin.Liu
# @Date   : 2019/1/4
# @Desc   : 数据库实体
from flask_sqlalchemy import SQLAlchemy

from blog.extensions import bcrypt

db = SQLAlchemy()

# 中间映射表
post_tags = db.Table("posts_tags",
                     db.Column("post_id", db.String(45), db.ForeignKey("posts.id")),
                     db.Column("tag_id", db.String(45), db.ForeignKey("tags.id")))


class User(db.Model):
    """系统用户"""
    __tablename__ = "users"
    id = db.Column(db.String(45), primary_key=True)
    username = db.Column(db.String(255))
    password = db.Column(db.String(255))
    # 建立关系,类似于hibernate对应关系
    posts = db.relationship('Post', backref='users', lazy='dynamic')

    def __init__(self, id, username, password):
        self.id = id
        self.username = username
        self.password = self.set_password(password)

    def __repr__(self):
        """自定义toString方法"""
        return "<User '{}'>".format(self.username)

    def set_password(self, password):
        """密码加密"""
        return bcrypt.generate_password_hash(password)

    def check_password(self, password):
        return bcrypt.check_password_hash(self.password, password)


class Post(db.Model):
    """发布的文章"""
    __tablename__ = "posts"
    id = db.Column(db.String, primary_key=True)
    title = db.Column(db.String(255))
    text = db.Column(db.Text())
    publish_date = db.Column(db.DateTime())
    user_id = db.Column(db.String(45), db.ForeignKey("users.id"))  # 指定外键

    # 一对多: Post ==> Comment
    # 和评价的外键建立联系: post_id
    comments = db.relationship(
        'Comment',
        backref='posts',
        lazy='dynamic')

    # 多对多: posts <==> tags
    # 关联表: posts_tags
    tags = db.relationship("Tag", secondary=post_tags, backref=db.backref("posts", lazy="dynamic"))

    def __init__(self, id, title):
        self.id = id
        self.title = title

    def __repr__(self):
        return "<Post> '{}'".format(self.title)


class Comment(db.Model):
    """用户评论"""
    __tablename__ = 'comments'
    id = db.Column(db.String(45), primary_key=True)
    name = db.Column(db.String(255))
    text = db.Column(db.Text())
    date = db.Column(db.DateTime())
    post_id = db.Column(db.String, db.ForeignKey("posts.id"))

    def __init__(self, id, name):
        self.id = id
        self.name = name

    def __repr__(self):
        return "<Comment '{}'>".format(self.name)


class Tag(db.Model):
    """产品标签"""

    __tablename__ = "tags"
    id = db.Column(db.String(45), primary_key=True)
    name = db.Column(db.String(255))

    def __init__(self, id, name):
        self.id = id
        self.name = name

    def __repr__(self):
        return "<Tag> '{}'".format(self.name)
